package edu.gatech.oad.publicstaticdroidmain.taskmanager.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import edu.gatech.oad.publicstaticdroidmain.taskmanager.model.TaskManager;

public class ManageCategoriesActivity extends AbstractTaskManagerActivity {

    private TaskManager taskManager;
    private ListView categoryListView;
    private Button add;

    private static final String[] CATEGORY_MODIFICATION_OPTIONS = { "Rename", "Delete" };
    private static final int RENAME_OPTION = 0;
    private static final int DELETE_OPTION = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.manage_categories);

	taskManager = ((TaskManagerApplication)(getApplication())).getTaskManager();
	OnClickListener buttonListener = new ManageCategoriesButtonListener();

	categoryListView = (ListView) findViewById(R.id.manageCategoriesListView);
	add = (Button) findViewById(R.id.manageCategoriesAddButton);

	add.setOnClickListener(buttonListener);
    }

    @Override
    public void onResume() {
	super.onResume();
	setUpCategoryList();
    }

    private void setUpCategoryList() {
	categoryListView.setOnItemClickListener(new CategorySelectedListener());
	categoryListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, taskManager.getCategories()));
	//categoryListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
	super.onPrepareOptionsMenu(menu);

	MenuItem manageCategories = menu.findItem(R.id.menu_manage_categories);

	manageCategories.setVisible(false);
	manageCategories.setEnabled(false);

	return true;
    }

    private void showCategoryRenameDialog(final String oldName) {
	final EditText input = new EditText(ManageCategoriesActivity.this);

	new AlertDialog.Builder(ManageCategoriesActivity.this)
	.setView(input)
	.setTitle("Rename \"" + oldName + "\"")
	.setPositiveButton("Rename", new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
		String newName = input.getText().toString().trim();
		taskManager.editCategoryName(oldName, newName);
		setUpCategoryList();
	    }
	})
	.setNegativeButton("Cancel", null)
	.show();
    }

    private void showCategoryDeleteDialog(final String catToDelete) {
	String[] currentCategories = taskManager.getCategories();
	
	if (currentCategories.length == 1) {
	    showErrorToast("You cannot delete the only category.");
	    return;
	}
	
	final String[] categoriesWithoutCatToDelete = new String[currentCategories.length - 1];
	
	int i = 0;
	for (String cat : currentCategories) {
	    if (!cat.equals(catToDelete) ) {
		categoriesWithoutCatToDelete[i++] = cat;
	    }
	}
	
	ArrayAdapter<String> categoryAdapter = new ArrayAdapter<String>(this, 
		android.R.layout.simple_spinner_item, 
		categoriesWithoutCatToDelete);

	final Spinner categoryChooser = new Spinner(ManageCategoriesActivity.this);
	categoryChooser.setAdapter(categoryAdapter);

	new AlertDialog.Builder(ManageCategoriesActivity.this)
	.setView(categoryChooser)
	.setTitle("Choose a Category")
	.setMessage("Choose the category into which " + catToDelete + "'s tasks will be moved.")
	.setPositiveButton("OK", new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
		int replacementIndex = categoryChooser.getSelectedItemPosition();
		String replacement = categoriesWithoutCatToDelete[replacementIndex];
		taskManager.removeCategory(catToDelete, replacement);
		setUpCategoryList();
	    }
	})
	.setNegativeButton("Cancel", null)
	.show();
    }

    private class CategorySelectedListener implements OnItemClickListener {

	public void onItemClick(AdapterView<?> adapter, View view, int pos, long id) {

	    final String oldCategoryName = (String) adapter.getItemAtPosition(pos);

	    new AlertDialog.Builder(ManageCategoriesActivity.this)
	    .setTitle("Modify \"" + oldCategoryName + "\"")
	    .setItems(CATEGORY_MODIFICATION_OPTIONS, new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int item) {
		    switch(item)
		    {
		    case RENAME_OPTION:
			showCategoryRenameDialog(oldCategoryName);
			break;
		    case DELETE_OPTION:
			showCategoryDeleteDialog(oldCategoryName);
			break;
		    }
		}
	    })
	    .show();
	}
    }

    private class ManageCategoriesButtonListener implements OnClickListener {

	public void onClick(View view) {
	    switch(view.getId()) {
	    case R.id.manageCategoriesAddButton:
		final EditText input = new EditText(ManageCategoriesActivity.this);

		new AlertDialog.Builder(ManageCategoriesActivity.this)
		.setTitle("Add Category")
		.setMessage(null)
		.setView(input)
		.setPositiveButton("Add", new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int whichButton) {
			String enteredText = input.getText().toString().trim();

			if (!enteredText.equals("")) {
			    taskManager.addCategory(enteredText);
			    setUpCategoryList();
			} 
		    }
		}).setNegativeButton("Cancel", null).show();

		break;
	    }
	}

    }
}
